﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using agsXMPP;
using agsXMPP.protocol.client;
using agsXMPP.Collections;
using agsXMPP.protocol.iq.roster;
using System.Threading;
using System.Xml;
using System.IO;

namespace WebChatClient.Controllers
{
    public class FBChatController : Controller
    {
        Jid jidSender;
        XmppClientConnection xmpp = new XmppClientConnection();

        List<FBMessage> InComingFBMessageList;
        XmlDocument SaveDoc;
        XmlDocument LoadDoc;
        

        //
        // GET: /FBChat/

        public ActionResult Index()
        {
            
            return View();
        }

        int flag = 0;

        //[HttpPost]
        //public void LoggInFacebook()
        //{
        //    jidSender = new Jid("leiduong@chat.facebook.com");
        //    xmpp = new XmppClientConnection(jidSender.Server);
        //    try
        //    {
        //        xmpp.Open(jidSender.User, "0908405204");
        //        xmpp.OnLogin += new ObjectHandler(xmpp_OnLogin);

        //    }
        //    catch (Exception ex)
        //    {
        //        //MessageBox.Show(ex.ToString());
        //    }
        //    while (flag == 0)
        //    {
        //    }
        //}



        public void xmpp_OnLogin(object sender)
        {
            //MessageBox.Show("Logged In");
            flag = 1;

        }


        string Receiver = null;
        //string SendText = null;
        string ReplyText = null;

        //[HttpPost]
        public string SendFacebook(string SendText)
        {

            //Loggin until flag = 1
            jidSender = new Jid("leiduong@chat.facebook.com");
            xmpp = new XmppClientConnection(jidSender.Server);
            try
            {
                xmpp.Open(jidSender.User, "0908405204"); //password
                xmpp.OnLogin += new ObjectHandler(xmpp_OnLogin);

            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
            }
            while (flag == 0)
            {
            }

            //Continue the work
           // SendText = Request["ChatText"];
            Receiver = "-100004640769599@chat.facebook.com"; // ID nguoi nhan

            //Trà : 100001649405310
            //Hậu :100000932858877
            //Hoàng: 1811700926
            //Huy: 1723633752
            //Nghi: 100000253751276
            //Duong 2 : 100004640769599

            if (xmpp.Authenticated == true)
            {
                Presence p = new Presence(ShowType.chat, "Online");
                p.Type = PresenceType.available;
                xmpp.Send(p);
            }

            xmpp.MessageGrabber.Add(new Jid(Receiver),
                                             new BareJidComparer(),
                                             new MessageCB(MessageCallBack),
                                             null);

            xmpp.Send(new agsXMPP.protocol.client.Message(new Jid(Receiver),
                      MessageType.chat,
                      SendText));
            return ReplyText;
        }

        public void MessageCallBack(object sender,
             agsXMPP.protocol.client.Message msg,
             object data)
        {
            FBMessage temp = new FBMessage();
            if (msg.Body != null)
            {
                temp.SenderID = Int64.Parse(msg.From.User);
                temp.BodyMessage = msg.Body;
                //InComingFBMessageList.Add(temp);
                SavetoXML(temp);
            }
        }

        public void SavetoXML(FBMessage fbmes)
        {
            SaveDoc = new XmlDocument();
            XmlElement el = (XmlElement)SaveDoc.AppendChild(SaveDoc.CreateElement("FBMessage"));
            el.SetAttribute("Body", fbmes.BodyMessage);
            el.SetAttribute("From", fbmes.SenderID.ToString());
            el.SetAttribute("Flag",fbmes.readflag.ToString() );

            //string path = Server.MapPath("FBFile.txt");
            SaveDoc.Save("FBtempFile.txt");
        }

        //PASS THE MESSAGE COMING TO THE AJAX POLLING IN VIEW
        [HttpGet]
        public Object getNewMesssage()
        {
            InComingFBMessageList = new List<FBMessage>();

            LoadDoc = new XmlDocument();

            if (System.IO.File.Exists("FBtempFile.txt"))
            {
                LoadDoc.Load("FBtempFile.txt");
            }

            XmlNodeList FbXMLlist= LoadDoc.SelectNodes("//FBMessage");
            
            foreach (XmlNode node in FbXMLlist)
            {
                FBMessage temp = new FBMessage();
                temp.BodyMessage = node.Attributes["Body"].Value;
                temp.SenderID = Int64.Parse(node.Attributes["From"].Value);
                temp.readflag = Int32.Parse(node.Attributes["Flag"].Value);
                InComingFBMessageList.Add(temp);
            }


            if (InComingFBMessageList.Count != 0)
            {
                FBMessage newMessage = InComingFBMessageList[InComingFBMessageList.Count - 1];
                if (newMessage.readflag != 1)
                {
                    newMessage.readflag = 1;
                    SavetoXML(newMessage);
                    return Json(newMessage.BodyMessage, JsonRequestBehavior.AllowGet);
                }
                
            }
            return Json("Failed", JsonRequestBehavior.AllowGet);
        }
    }
}
